package main

import (
	"fmt"
	"net"
	"time"
	. "zinx-learn/znet"
)

func Client() {
	addr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:7777")
	if err != nil {
		fmt.Println("ResolveTCPAddr error", err.Error())
		return
	}
	conn, err := net.DialTCP("tcp4", nil, addr)
	if err != nil {
		fmt.Println("conn server error", err.Error())
		return
	}

	dp := NewDataPack()
	go func() {
		for {
			msg, err := dp.ConnToMsg(conn)
			if err != nil {
				fmt.Println("ConnToMsg error ", err.Error())
				return
			}
			fmt.Println(string(msg.GetData()))
		}
	}()
	for i := 0; i < 10; i++ {
		s := fmt.Sprintf("你好，Zinx %d", i)
		var message *Message
		message = NewMessage(10, []byte(s))
		data, err := dp.Pack(message)
		if err != nil {
			fmt.Println("pack message error")
			continue
		}
		_, err = conn.Write(data)
		if err != nil {
			fmt.Println("write error err", err.Error())
			return
		}
		time.Sleep(time.Second)
	}

}

func main() {
	Client()

}
